<template>
  <div class="m-view-qualityInspection m-window" ref="elementId">
    <!-- 搜索条件 -->
    <div class="m-condition" v-show="!componentsShow">
      <el-row :gutter="10">
        <el-form
          :model="ruleForm"
          ref="ruleForm"
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
          <!-- 公司  -->
          <el-col :span="6">
            <el-form-item label="公司" class="rightItem">
              <el-select
                value-key="id"
                v-model="ruleForm.selCompanyCode"
                placeholder="请选择公司"
                @change="companyChange"
                ref="content"
                filterable
                clearable
              >
                <el-option
                  v-for="item in comOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 采购单号 -->
          <el-col :span="4">
            <el-form-item label="采购单号" class="rightItem">
              <el-input
                v-model="ruleForm.purOrderNo"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 送货单号 -->
          <el-col :span="4">
            <el-form-item label="送货单号" class="rightItem">
              <el-input
                v-model="ruleForm.deliveryNo"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 审核日期 -->
          <el-col :span="6">
            <el-form-item label="审核日期" class="rightItem">
              <el-date-picker
                v-model="ruleForm.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                clearable
                :picker-options="po1"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="ruleForm.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              clearable
              :picker-options="po2"
            ></el-date-picker>
          </el-col>
          <!-- 供应商  -->
          <el-col :span="6" v-if="isInnerUser">
            <el-form-item label="供应商" class="rightItem">
              <supplier
                :layout="layout"
                :supplierInfo.sync="ruleForm.supplier"
              />
              <!-- @search="search('init')" -->
            </el-form-item>
          </el-col>
          <!-- 物料编号 -->
          <el-col :span="!isInnerUser ? 5 : 4">
            <el-form-item label="物料编号" class="rightItem">
              <el-input
                v-model="ruleForm.matCode"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 物料名称 -->
          <el-col :span="!isInnerUser ? 5 : 4">
            <el-form-item label="物料名称" class="rightItem">
              <el-input
                v-model="ruleForm.matName"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 入库凭证 -->
          <el-col :span="!isInnerUser ? 5 : 4">
            <el-form-item label="入库凭证" class="rightItem">
              <el-input
                v-model="ruleForm.matVoucher"
                clearable
                @keyup.enter.native="search('init')"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- 质检结果 -->
          <el-col :span="4">
            <el-form-item label="质检结果" class="rightItem">
              <el-select
                v-model="ruleForm.billState"
                @change="search('init')"
                clearable
              >
                <el-option
                  v-for="item in insResults"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="m-floatRight">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-button
                  type="primary"
                  @click="search('init')"
                  :disabled="btnDis"
                  >查询</el-button
                >
              </el-col>
              <el-col :span="12">
                <el-button
                  type="primary"
                  @click="search('import')"
                  :disabled="importBtnDis"
                  :loading="importLoading"
                  >{{
            importLoading ? "导出中..." : "导出"
          }}</el-button
                >
              </el-col>
            </el-row>
          </el-col>
        </el-form>
      </el-row>
    </div>
    <!-- aggrid -->
    <div
      :class="[
        'm-agTable m-bottom',
        { 'g-top150': !isInnerUser, 'g-top180': isInnerUser }
      ]"
      v-show="!componentsShow"
    >
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="tableData"
        v-loading="loading"
        rowSelection="single"
      ></ag-grid-vue>
    </div>
    <!-- 页码 -->
    <div class="m-page" v-show="!componentsShow">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handleCurrentChange"
        @next-click="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <inspectHis
      v-if="componentsShow"
      class="m-window"
      @back="back"
      :queryParams="queryParams"
    />
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";
import inspectHis from "./common/inspectHis";
import supplier from "@/components/supplier";
import serviceTime from "@/public/serverTime.js";
import constant from "@/public/constant";
import { exportExcel } from "lesso-common/public/utils";
import Msg from "@/public/message.js";

console.log(constant);

export default {
  data() {
    return {
      layout: {
        companyCode: ""
      },
      ruleForm: {
        supplier: {},
        selCompanyCode: {},
        startDate: '',
        endDate: '',
      },
      comOptions: [], // 公司列表
      insResults: [
        { label: "未检", value: "0" },
        { label: "合格", value: "10" },
        { label: "复检", value: "20" },
        { label: "不合格", value: "30" },
        { label: "让步接收", value: "40" },
        { label: "换货中", value: "50" },
        { label: "换货合格", value: "60" },
        { label: "退货", value: "70" }
      ],
      btnDis: false,
      importBtnDis: false,
      importLoading: false,
      po1: {
        disabledDate: this.disabledDate1
      },
      po2: {
        disabledDate: this.disabledDate2
      },
      currentPage: 1,
      pageSize: 30,
      total: 0,
      loading: false,
      tableData: [],
      componentsShow: false,
      queryParams: {},
      // 用户类型,4为供应商，1为内部用户
      isInnerUser: this.$global.user.userTypeId == 1
    };
  },
  methods: {
    handleSizeChange(pageSize) {
      this.currentPage = 1;
      this.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.search();
    },
    // 导出列表数据
    exportData() {
      let excelData = [];
      let fileName = `质检结果报表.xlsx`;
      this.exportQueryData.forEach(row => {
        excelData.push({
          公司: row.werksName,
          采购订单号: (row.orderNo || '').toString(),
          行项目号: row.lineProjects,
          送货单号: (row.deliveryNo || '').toString(),
          入库凭证: (row.matVoucher || '').toString(),
          入库凭证行号: (row.orderLineProjects || '').toString(),
          物料编码: (row.matCode || '').toString(),
          物料名称: row.matName,
          采购员: row.purGroupName,
          检验日期: row.storeDate,
          检验结果: row.billStateText
        });
      });
      let params = {
        data: excelData,
        fileName
      };
      exportExcel(params);
    },
    findLabel(val, arr) {
      for (let { label, value } of arr) {
        if (value == val) {
          return label;
        }
      }
    },
    // 查询
    search(type) {
      if (type === "init") {
        this.currentPage = 1;
      }
      if (type !== "import") {
        this.tableData = [];
        this.loading = true;
        this.btnDis = true;
      } else {
        this.importLoading = true;
        this.importBtnDis = true;
      }

      let params = {
        current: type === "import" ? 1 : this.currentPage,
        pageSize: type === "import" ? 100000 : this.pageSize,
        companyCode: this.ruleForm.selCompanyCode.companyCode,
        // 内部用户，自己选择供应商，外部用户，默认供应商
        supplierCode: this.isInnerUser
          ? this.ruleForm.supplier.supplierCode
          : (constant.supplierData || {}).supplierCode,
        ...this.ruleForm,
        startDate: this.ruleForm.startDate
          ? `${this.ruleForm.startDate} 00:00:00.0`
          : "",
        endDate: this.ruleForm.endDate
          ? `${this.ruleForm.endDate} 00:00:00.0`
          : ""
      };
      _Api
        .queryQuaRes(params)
        .then(({ data }) => {
          this.loading = false;
          this.importLoading = false;
          if(type !== "import") {
            this.btnDis = false;
          } else {
            this.importBtnDis = false;
          }
          if (data.code === 1) {
            data.rows.forEach(row => {
              row.billStateText = this.findLabel(
                row.billState,
                this.insResults
              );
              row.isFail = row.billState != 10;
              if(type !== "import") {
                this.tableData.push(row);
              }
            });
            if (type === "import") {
              this.exportQueryData = data.rows;
              this.exportData();
            } else {
              this.total = data.total;
            }
          } else {
            Msg.showErrorMsg(data.info);
          }
        })
        .catch(err => {
          this.loading = false;
          this.btnDis = false;
          this.importLoading = false;
          this.importBtnDis = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    companyChange(item) {
      this.layout.companyCode = item.companyCode;
      this.layout.auth = true;
      this.search("init");
    },
    disabledDate1(time) {
      if (this.ruleForm.endDate)
        return time.getTime() > new Date(this.ruleForm.endDate).getTime();
    },
    disabledDate2(time) {
      if (this.ruleForm.startDate)
        return (
          time.getTime() <
          new Date(this.ruleForm.startDate).getTime() - 3600 * 1000 * 24
        );
    },
    // 查看详情
    viewDetail(rowData) {
      console.log(rowData);
      this.queryParams = rowData;
      this.componentsShow = true;
    },
    back() {
      this.componentsShow = false;
    },
    initData() {
      //查询公司列表
      var obj = {};
      if (constant.user.userTypeId == 4) {
        obj.account = constant.user.userName;
        obj.userType = 2;
      } else {
        obj.account = constant.user.oaNum;
        obj.userType = 1;
      }
      var that = this;
      _Api
        .getAuthInfo(obj)
        .then(function(response) {
          var data = response.data;
          if (data.code == "1") {
            that.comOptions = data.rows.myMstCompany;
            //默认公司
            if (constant.user.userTypeId != 4) {
              //找登录人所在公司的条目
              for (var i = 0; i < that.comOptions.length; i++) {
                if (that.comOptions[i].companyCode == constant.user.bukrs) {
                  that.ruleForm.selCompanyCode = that.comOptions[i];
                  break;
                }
              }
            }
            that.layout.companyCode = that.ruleForm.selCompanyCode.companyCode;
            that.layout.auth = true;
          }
        })
        .catch(err => {
          Msg.showErrorMsg(err.data.message);
          that.comOptions = [];
        });
    },
    initControl() {
      //默认日期范围 三个月
      serviceTime.getServiceTime().then(serviceTime => {
        if (serviceTime) {
          this.ruleForm.startDate = new Date(
            serviceTime.getTime() - 30 * 24 * 3600 * 1000
          ).Format("yyyy-MM-dd");
          this.ruleForm.endDate = serviceTime.Format("yyyy-MM-dd");
        }
      });
    }
  },
  beforeMount() {
    this.gridOptions = Object.assign(
      {
        context: {
          componentParent: this
        },
        localeText: localeText,
        suppressRowClickSelection: true,
        //   getContextMenuItems: this.getContextMenuItems,
        enableColResize: true,
        onGridReady: function($event) {
          // that.gridOptions.api.sizeColumnsToFit();
        }
      },
      gridOptions()
    );
    this.columnDefs = [
      {
        headerName: "公司",
        field: "werksName",
        width: 180
      },
      {
        headerName: "采购订单号",
        field: "orderNo",
        width: 100
      },
      {
        headerName: "行项目号",
        field: "lineProjects",
        width: 100
      },
      {
        headerName: "送货单号",
        field: "deliveryNo",
        width: 100
      },
      {
        headerName: "入库凭证",
        field: "matVoucher",
        width: 100
      },
      {
        headerName: "入库凭证行号",
        field: "orderLineProjects",
        width: 120
      },
      {
        headerName: "物料编码",
        field: "matCode",
        width: 100
      },
      {
        headerName: "物料名称",
        field: "matName",
        width: 180
      },
      {
        headerName: "采购员",
        field: "purGroupName",
        width: 80
      },
      {
        headerName: "检验日期",
        field: "storeDate",
        width: 150
      },
      {
        headerName: "检验结果",
        field: "billStateText",
        width: 100,
        cellRendererFramework: "OperateComponent",
        pinned: 'right'
      }
    ];
  },
  components: {
    OperateComponent: {
      template: `
            <div>
              <span style="cursor: pointer;display: block;" :class="{'m-danger': params.data.isFail}" @click="viewDetail">{{params.data.billStateText}}</span>
            </div>
          `,
      methods: {
        viewDetail() {
          this.params.context.componentParent.viewDetail(this.params.node.data);
        }
      }
    },
    inspectHis,
    supplier
  },
  mounted() {
    // 初始化控件
    this.initControl();
    //初始化数据源
    this.initData();
  }
};
</script>
